<?php
class Action{
	
	public static $msgs = array();
		
	function __construct()
	{
	
	}
	
	
	function updateUser($data)
	{
		global $db;
		$user_id = (int) $data['user_id'];
		if( $user_id > 0 )
		{
			$record = array(
									'name' => $data['name'],
									'email'=> $data['email'],
									'phone_no'=> $data['phone_no'],
									'gender'=> $data['gender'],
								);
			$where = array('user_id' => $user_id);
			$db->update("trivia_users", $record, $where);
			echo $user_id; exit;
		}
		echo 0;
	}
	
	 public function addUser($data)
    {
		global $db, $msgError;
		$data['imei_no'] = trim($data['imei_no']);
		if($data['imei_no'] != '')
		{
			$user_data = $db->first("SELECT * FROM trivia_users  WHERE imei_no = '".$db->escape($data['imei_no'])."'");
			if( intval($user_data['user_id']) > 0 ) // user already exist
			{
				$username = $user_data['username'];
			}
			else	// add new user
			{
				 $record = array('imei_no' => $data['imei_no']);
				 $user_id =  $db->insert("trivia_users", $record); 		
				 $ran_str = $this->get_rand_id(6);
				 $username = strtoupper($ran_str)."-".$user_id;
				 
				 $record = array('username' => $username);
				 $where = array('user_id' => $user_id);
				 $db->update("trivia_users", $record, $where);
			}	
			echo $username; exit;
		}
			echo 0; exit;
	}
	
	function getCategoriesXML()
	{
		global $db, $config;
		$sql = "SELECT * FROM category order by category_name ";
		$result = $db->fetch_all($sql);	
		$xml = "<categories>";
		foreach($result as $row)
		{
			$xml .= "<category>
							<category_id>".$row['category_id']."</category_id>
							<category_name>".trim($row['category_name'])."</category_name>
						</category>	";	
		}
		$xml .= "</categories>";
		
		header ("content-type: text/xml");
		echo $xml;
		exit;
		
	}
	
	function getQuestions($data)
	{
		global $db;
		$category_id = $data['category_id'];
		$user_id = $data['user_id'];
		$question_level = $data['question_level'];
		$limit = $data['no_of_question'];
		
		if($limit == '' ){
			$limit = " limit 0, 3 ";
		} else {
			$limit = " limit 0, ".intval($limit)." ";	
		}
		
		$sql = "SELECT 
						DISTINCT q. * FROM quiz_question q 
				WHERE q.active = 1 AND q.question_level = '".$question_level."' AND q.category_id = '".$category_id."' AND q.question_id NOT IN ( SELECT a.question_id	FROM quiz_answer a WHERE a.user_id ='".$user_id."' ) $limit ";
				
		$questions = $db->fetch_all($sql);
		
		$xml = "<trivia>";
		
		foreach($questions as $row)
		{
			$xml .= "<question>
						<question_id>".$row['question_id']."</question_id>
						<question_stmt>".$row['question']."</question_stmt>
					   <answer_id>".$row['answer_id']."</answer_id>
						 <option>";
			
			$options = $this->getQuestionOptions($row['question_id']);
			foreach($options as $opt)
			{
				$xml .= "<option_id>".$opt['quiz_option_id']."</option_id>
				        <option_stmt>".$opt['quiz_option']."</option_stmt>";
			}
			
			$xml .= "</option></question>";
			
		}
		$xml .= "</trivia>";
		
		header ("content-type: text/xml");
		echo $xml;
		exit;
	}
	
	function getQuestionOptions($question_id)
	{
		global $db;
		$sql = "SELECT * FROM quiz_option WHERE question_id = '".$question_id."'";
		return $db->fetch_all($sql);		
	}
	
	function submitTrivia($data)
	{
		global $db;
		$success = 0;
		$user_id = (int)$data['user_id'];
		if( $user_id > 0 )
		{
			$questions = explode(',', $data['questions']);
			$answers = explode(',', $data['answers']);
			$points = explode(',', $data['points']);
			$created_on = date('Y-m-d H:i:s');
			$set_id = $this->getTrivaSetId();
			
			for($i = 0; $i < count($questions); $i++ )
			{
				if( intval($questions[$i]) > 0 )
				{
						$record = array(
						  'user_id' => $user_id,
						  'question_id' => $questions[$i],
						  'correct' => $answers[$i],
						  'set_id' => $set_id,
						  'points' => $points[$i],
						  'created_on' => $created_on
						);
					
					$db->insert("quiz_answer", $record);	
					$success = 1;
				}
			}	
			
		}
		echo $success;
	}
	
	function getTrivaSetId()
	{
		global $db;
		$sql = "SELECT max(set_id) as max_id FROM quiz_answer limit 1";
		$data = $db->first($sql);
		$set_id = intval($data['max_id']) + 1;
		return $set_id;
	}
	
	function submitQuestions($data)
	{
		global $db;
		//category_id, user_id,question_stmt,answers(array), with correct answer no( id)
		
	
			 $record = array(
			 				 'category_id' => $data['category_id'],	
						  	 'question' => $data['question_stmt'],
							 'question_level' => intval($data['question_level']),
							 'active' => 0,
							 'created_by' => $user_id, 
						  	 'created_on' => date('Y-m-d H:i:s')
					       );
		   
		   	 $question_id = $db->insert("quiz_question", $record);
			 
			 
			 if( count($data['answers']) > 0 )
			 {
				 foreach($data['answers'] as $quiz_option)
				 { 
				      $record = array('question_id' =>$question_id,'quiz_option' => $quiz_option);
				 	  $db->insert("quiz_option", $record);
				 }
			 }
			 $sql = "SELECT quiz_option_id FROM quiz_option
			 		 WHERE  question_id = '".$question_id."'
					 AND quiz_option = '".($data['answers'][$data['answer_index']])."'";
			 $trivia_option_id = $db->first($sql);
			//print $db->last_query();exit;
			$quiz_option_id = $trivia_option_id['quiz_option_id'];
			 /*=== this query update answer_id in quiz_questin table*/
			 $update_record_answer = array('answer_id' => $quiz_option_id);
			 $where = array( "question_id" =>$question_id );
			 //print $db->last_query();exit;
			 $db->update("quiz_question", $update_record_answer, $where);
			
			echo 1;
			
			//==========================================================
		

		
	 
		
	
	}
	
	function ideaByUser($data)
	{
		global $config;
		require($config['basedir']."/admin/classes/common.modules.class.php");
		$obj_cm = new CommonModules('ideaByUser');
		echo $obj_cm->save($data);
	}
	
	function issueByUser($data)
	{
		global $config;
		require($config['basedir']."/admin/classes/common.modules.class.php");
		$obj_cm = new CommonModules('issueByUser');
		echo $obj_cm->save($data);
	}
	
	function questionByUser($data)
	{
		global $config;
		require($config['basedir']."/admin/classes/common.modules.class.php");
		$obj_cm = new CommonModules('questionByUser');
		echo $obj_cm->save($data);
	}
	
	function saveImageToServer($data)
	{
		global $db, $config;
		$user_id = (int) $data['user_id'];
		if( $user_id > 0 )
		{
			$base = $data['image_string'];
			$binary = base64_decode($base);
			$image_ext = $data['image_type'];
			$image_name = $data['user_id']."_pimg.".$image_ext;
			$image_path = $config['basedir']  ."/images/profile/".$image_name;
			$file = fopen($image_path, 'w');			
			
			if( fwrite($file, $binary) )
			{
				fclose($file);
				if(copy($image_name,$config['basedir']  ."/images/profile/".$image_name.$image_ext)){
					unlink($image_name);
				}			
 				$record = array( 'profile_img' => $image_name);
				$where = array('user_id' => $user_id);
				$db->update("trivia_users", $record, $where);
 				echo 1;
				exit;
			}
		}
			
		echo 0; exit;
	}
	
	function getUserInfo($data)
	{
		global $config;
		$user_id = (int) $data['user_id'];
		if( $user_id > 0 )
		{
			$user_data = $this->getUserById($user_id);	
			if( $user_data['profile_img'] != '' ){
				$img_path = $config['baseurl']."/images/profile/".$user_data['profile_img'];
			} else {
				$img_path = '';
			}
			$xml = "<userinfo>";
			$xml .= "<name>".$user_data['name']."</name>";
			$xml .= "<username>".$user_data['username']."</username>";
			$xml .= "<email>".$user_data['email']."</email>";
			$xml .= "<phone_no>".$user_data['phone_no']."</phone_no>";
			$xml .= "<imei_no>".$user_data['imei_no']."</imei_no>";
			$xml .= "<gender>".$user_data['gender']."</gender>";
			$xml .= "<profile_img>".$img_path."</profile_img>";
 			$xml .= "</userinfo>";
			header ("content-type: text/xml");
			echo $xml;
			exit;
		}
		
		echo 0; exit;
	}
	
	function getTopScorerByCategory($data)
	{
		global $db, $config;
		$category_id = $data['category_id'];
		$sql = "SELECT u . * , sum( a.points ) AS score
					FROM trivia_users u, `quiz_answer` a, quiz_question q
					WHERE q.question_id = a.question_id
					AND q.category_id = '".$category_id."'
					AND a.user_id = u.user_id
					GROUP BY u.user_id
					ORDER BY score DESC
					LIMIT 0 , 3 ";
		
		$result = $db->fetch_all($sql);	
		
		$xml = "<topscorers>";
		foreach($result as $row)
		{
			if( $row['profile_img'] != '' ){
				$img_path = $config['baseurl']."/images/profile/".$row['profile_img'];
			} else {
				$img_path = '';
			}
			
			$xml .= "<userinfo>";
			$xml .= "<score>".$row['score']."</score>";
			$xml .= "<name>".$row['name']."</name>";
			$xml .= "<username>".$row['username']."</username>";
			$xml .= "<email>".$row['email']."</email>";
			$xml .= "<phone_no>".$row['phone_no']."</phone_no>";
			$xml .= "<imei_no>".$row['imei_no']."</imei_no>";
			$xml .= "<gender>".$row['gender']."</gender>";
			$xml .= "<profile_img>".$img_path."</profile_img>";
 			$xml .= "</userinfo>";
		}
		$xml .= "</topscorers>";
		
		header ("content-type: text/xml");
		echo $xml;
		exit;
		
	}
	
	function getUserById($user_id)
	{
		global $db, $config;
		$sql = "SELECT * FROM trivia_users where user_id = '".$user_id."' ";
		return $db->first($sql);
	}
	
	function getToDayBanner($data)
	{
		global $db, $config;
		$sql = "SELECT * FROM banners WHERE status = 1 ORDER BY RAND()" ;
        $banner_data = $db->fetch_all($sql);	
		$xml = "<banners>";
		foreach( $banner_data as $row )
		{
			$img_path = $config['baseurl']."/images/banners/".$row['banner_image'];
			$xml .= "<banner>";
			$xml .= "<banner_name>".$row['banner_name']."</banner_name>";
			$xml .= "<banner_link>".$row['banner_link']."</banner_link>";
			$xml .= "<banner_image>".$img_path."</banner_image>";
			$xml .= "</banner>";
			
		}
		$xml .= "</banners>";
		header ("content-type: text/xml");
		echo $xml;
		exit;
		
		echo 0; exit;	
	}
	
	function getLatestIssues()
	{
		global $db, $config;
		$category_id = $data['category_id'];
		$sql = "SELECT *, date_format(created_on, '%m-%d-%Y') as submit_date FROM user_issues t INNER JOIN trivia_users u ON ( t.user_id = u.user_id ) ORDER BY id DESC LIMIT 0 , 10 ";
		$result = $db->fetch_all($sql);	
		$xml = "<issues>";
		foreach($result as $row)
		{
			if( $row['profile_img'] != '' ){
				$img_path = $config['baseurl']."/images/profile/".$row['profile_img'];
			} else {
				$img_path = '';
			}
			
			$xml .= "<issue>";
			$xml .= "<issue_stmt><![CDATA[".$row['issue_stmt']."]]></issue_stmt>";
			$xml .= "<issue_description><![CDATA[".$row['issue_description']."]]></issue_description>";
			$xml .= "<created_on>".$row['submit_date']."</created_on>";
			$xml .= "<name>".$row['name']."</name>";
			$xml .= "<user_id>".$row['user_id']."</user_id>";
			$xml .= "<profile_img>".$img_path."</profile_img>";
 			$xml .= "</issue>";
		}
		$xml .= "</issues>";
		header ("content-type: text/xml");
		echo $xml;
		exit;	
	}
	
	function mostCommonIssues()
	{
		global $db, $config;
		$category_id = $data['category_id'];
		$sql = "SELECT *, date_format(created_on, '%m-%d-%Y') as submit_date FROM user_issues t INNER JOIN trivia_users u ON ( t.user_id = u.user_id ) ORDER BY id DESC LIMIT 10 , 20 ";
		$result = $db->fetch_all($sql);	
		
		if( count($result) < 1 ) {
			$this->getLatestIssues(); exit;
		}
		
		$xml = "<issues>";
		foreach($result as $row)
		{
			if( $row['profile_img'] != '' ){
				$img_path = $config['baseurl']."/images/profile/".$row['profile_img'];
			} else {
				$img_path = '';
			}
			
			$xml .= "<issue>";
			$xml .= "<issue_stmt><![CDATA[".$row['issue_stmt']."]]></issue_stmt>";
			$xml .= "<issue_description><![CDATA[".$row['issue_description']."]]></issue_description>";
			$xml .= "<created_on>".$row['submit_date']."</created_on>";
			$xml .= "<name>".$row['name']."</name>";
			$xml .= "<user_id>".$row['user_id']."</user_id>";
			$xml .= "<profile_img>".$img_path."</profile_img>";
 			$xml .= "</issue>";
		}
		$xml .= "</issues>";
		header ("content-type: text/xml");
		echo $xml;
		exit;	
	}
	
	function getLatestIdeas()
	{
		global $db, $config;
		$category_id = $data['category_id'];
		$sql = "SELECT *, date_format(created_on, '%m-%d-%Y') as submit_date FROM user_ideas t INNER JOIN trivia_users u ON ( t.user_id = u.user_id ) ORDER BY id DESC LIMIT 0 , 10 ";
		$result = $db->fetch_all($sql);	
		$xml = "<ideas>";
		foreach($result as $row)
		{
			if( $row['profile_img'] != '' ){
				$img_path = $config['baseurl']."/images/profile/".$row['profile_img'];
			} else {
				$img_path = '';
			}
			
			$xml .= "<idea>";
			$xml .= "<idea_stmt><![CDATA[".$row['idea_stmt']."]]></idea_stmt>";
			$xml .= "<idea_description><![CDATA[".$row['idea_description']."]]></idea_description>";
			$xml .= "<created_on>".$row['submit_date']."</created_on>";
			$xml .= "<name>".$row['name']."</name>";
			$xml .= "<user_id>".$row['user_id']."</user_id>";
			$xml .= "<profile_img>".$img_path."</profile_img>";
 			$xml .= "</idea>";
		}
		$xml .= "</ideas>";
		header ("content-type: text/xml");
		echo $xml;
		exit;	
	}
	
	function mostCommonIdeas()
	{
		global $db, $config;
		$category_id = $data['category_id'];
		$sql = "SELECT *, date_format(created_on, '%m-%d-%Y') as submit_date FROM user_ideas t INNER JOIN trivia_users u ON ( t.user_id = u.user_id ) ORDER BY id DESC LIMIT 10 , 20 ";
		$result = $db->fetch_all($sql);	
		
		if( count($result) < 1 ) {
			$this->getLatestIdeas(); exit;
		}
		
		$xml = "<ideas>";
		foreach($result as $row)
		{
			if( $row['profile_img'] != '' ){
				$img_path = $config['baseurl']."/images/profile/".$row['profile_img'];
			} else {
				$img_path = '';
			}
			
			$xml .= "<idea>";
			$xml .= "<idea_stmt><![CDATA[".$row['idea_stmt']."]]></idea_stmt>";
			$xml .= "<idea_description><![CDATA[".$row['idea_description']."]]></idea_description>";
			$xml .= "<created_on>".$row['submit_date']."</created_on>";
			$xml .= "<name>".$row['name']."</name>";
			$xml .= "<user_id>".$row['user_id']."</user_id>";
			$xml .= "<profile_img>".$img_path."</profile_img>";
 			$xml .= "</idea>";
		}
		$xml .= "</ideas>";
		header ("content-type: text/xml");
		echo $xml;
		exit;	
	}
	
	function getLatestQuestionByUsers()
	{
		global $db, $config;
		$category_id = $data['category_id'];
		$sql = "SELECT *, date_format(created_on, '%m-%d-%Y') as submit_date FROM user_questions t INNER JOIN trivia_users u ON ( t.user_id = u.user_id ) ORDER BY id DESC LIMIT 0 , 10 ";
		$result = $db->fetch_all($sql);	
		$xml = "<questions>";
		foreach($result as $row)
		{
			if( $row['profile_img'] != '' ){
				$img_path = $config['baseurl']."/images/profile/".$row['profile_img'];
			} else {
				$img_path = '';
			}
			
			$xml .= "<question>";
			$xml .= "<question_stmt><![CDATA[".$row['question_stmt']."]]></question_stmt>";
			$xml .= "<question_description><![CDATA[".$row['question_description']."]]></question_description>";
			$xml .= "<created_on>".$row['submit_date']."</created_on>";
			$xml .= "<name>".$row['name']."</name>";
			$xml .= "<user_id>".$row['user_id']."</user_id>";
			$xml .= "<profile_img>".$img_path."</profile_img>";
 			$xml .= "</question>";
		}
		$xml .= "</questions>";
		header ("content-type: text/xml");
		echo $xml;
		exit;	
	}
	
	function mostCommonQuestionByUsers()
	{
		global $db, $config;
		$category_id = $data['category_id'];
		$sql = "SELECT *, date_format(created_on, '%m-%d-%Y') as submit_date FROM user_questions t INNER JOIN trivia_users u ON ( t.user_id = u.user_id ) ORDER BY id DESC LIMIT 10 , 20 ";
		$result = $db->fetch_all($sql);	
		
		if( count($result) < 1 ) {
			$this->getLatestQuestionByUsers(); exit;
		}
		
		$xml = "<questions>";
		foreach($result as $row)
		{
			if( $row['profile_img'] != '' ){
				$img_path = $config['baseurl']."/images/profile/".$row['profile_img'];
			} else {
				$img_path = '';
			}
			
			$xml .= "<question>";
			$xml .= "<question_stmt><![CDATA[".$row['question_stmt']."]]></question_stmt>";
			$xml .= "<question_description><![CDATA[".$row['question_description']."]]></question_description>";
			$xml .= "<created_on>".$row['submit_date']."</created_on>";
			$xml .= "<name>".$row['name']."</name>";
			$xml .= "<user_id>".$row['user_id']."</user_id>";
			$xml .= "<profile_img>".$img_path."</profile_img>";
 			$xml .= "</question>";
		}
		$xml .= "</questions>";
		header ("content-type: text/xml");
		echo $xml;
		exit;	
	}
	
	function get_rand_id($length)
	{
		if($length>0)
		{
			$rand_id="";
			for($i=1; $i<=$length; $i++)
			{
				mt_srand((double)microtime() * 1000000);
				$num = mt_rand(1,26);
				$rand_id .= $this->assign_rand_value($num);
			}
		}
		return $rand_id;
	}
		
	function assign_rand_value($num)
	{
	
		switch($num)
		{
			case "1":
				$rand_value = "a";
				break;
			case "2":
				$rand_value = "b";
				break;
			case "3":
				$rand_value = "c";
				break;
			case "4":
				$rand_value = "d";
				break;
			case "5":
				$rand_value = "e";
				break;
			case "6":
				$rand_value = "f";
				break;
			case "7":
				$rand_value = "g";
				break;
			case "8":
				$rand_value = "h";
				break;
			case "9":
				$rand_value = "i";
				break;
			case "10":
				$rand_value = "j";
				break;
			case "11":
				$rand_value = "k";
				break;
			case "12":
				$rand_value = "l";
				break;
			case "13":
				$rand_value = "m";
				break;
			case "14":
				$rand_value = "n";
				break;
			case "15":
				$rand_value = "o";
				break;
			case "16":
				$rand_value = "p";
				break;
			case "17":
				$rand_value = "q";
				break;
			case "18":
				$rand_value = "r";
				break;
			case "19":
				$rand_value = "s";
				break;
			case "20":
				$rand_value = "t";
				break;
			case "21":
				$rand_value = "u";
				break;
			case "22":
				$rand_value = "v";
				break;
			case "23":
				$rand_value = "w";
				break;
			case "24":
				$rand_value = "x";
				break;
			case "25":
				$rand_value = "y";
				break;
			case "26":
				$rand_value = "z";
				break;
			case "27":
				$rand_value = "0";
				break;
			case "28":
				$rand_value = "1";
				break;
			case "29":
				$rand_value = "2";
				break;
			case "30":
				$rand_value = "3";
				break;
			case "31":
				$rand_value = "4";
				break;
			case "32":
				$rand_value = "5";
				break;
			case "33":
				$rand_value = "6";
				break;
			case "34":
				$rand_value = "7";
				break;
			case "35":
				$rand_value = "8";
				break;
			case "36":
				$rand_value = "9";
				break;
		}
		return $rand_value;
	}
	
  
}


?>